package com.example.demo.utility;

import com.example.demo.pojo.ChatGroupPO;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.Set;

/**
 * redis配置类
 */
public class RedisUtil {

    //    private static final String HOST = "127.0.0.1";
    private static final String HOST = "123.57.23.218";
    private static final int PORT = 6379;
    private static final String PASSWORD = "123456";
    private Jedis jedis;

    public RedisUtil(){
        jedis = new Jedis(HOST,PORT);
    }
    //设置
    public void set(String key,String value,int seconds){
        jedis.auth(PASSWORD);
        jedis.setex(key,seconds, value);
    }
    //根据键查询
    public String get(String key){
        jedis.auth(PASSWORD);
        return jedis.get(key);
    }
    //根据前缀名查询全部键
    public ArrayList<ChatGroupPO> getKeyByPrefix(String prefix) {
        jedis.auth(PASSWORD);
        ArrayList<ChatGroupPO> arrayList = new ArrayList<>();
        Set<String> keys = jedis.keys(prefix + "*");
        for (String key : keys) {
            String value = jedis.get(key);
            ChatGroupPO entry = new ChatGroupPO(key, value);
            arrayList.add(entry);
        }
        return arrayList;
    }
    //设置键值的过期时间
    public void expire(String key,int seconds){
        jedis.auth(PASSWORD);
        jedis.expire(key,seconds);
    }
    public void close(){
        jedis.auth(PASSWORD);
        jedis.close();
    }

}
